import type { CollapseProps } from 'antd';
import { Checkbox, Collapse } from 'antd';
import { memo, useMemo, useRef, useState } from 'react';
import OStyle from './index.less';
import IndustrySel, { TradeType } from './IndustrySel';

function TradeGroupSelect(props: { value?: TradeType[]; onChange: any }) {
  //   const [showTrade, setShowTrade] = useState<TradeType[]>([]);
  const [code, setCode] = useState<string>('');
  const [indeterminate, setIndeterminate] = useState<boolean>(false);
  const [isChecked, setIsChecked] = useState<boolean>(false);
  const industryRef = useRef<any>(null);
  const [tradeLen, setTradeLen] = useState<number>(0);

  const items: CollapseProps['items'] = useMemo(() => {
    return [
      {
        key: 'all',
        label: (
          <Checkbox
            indeterminate={indeterminate}
            onChange={(e) => {
              industryRef.current?.allSelect(e.target.checked);
            }}
            checked={tradeLen ? isChecked : false}
          >
            已选({code ? code.split(',').length : 0})
          </Checkbox>
        ),
        children: (
          <>
            <IndustrySel
              innerRef={industryRef}
              initChange={(len: number) => {
                setTradeLen(len);
              }}
              defaultValue={props.value ? props.value : []}
              onChange={(e: { showTrade: any; tradeName: any; code: any; isAllCheck: any }) => {
                props.onChange({
                  showTrade: e.showTrade,
                  tradeName: e.tradeName,
                  code: e.code,
                });
                console.log('isAllCheck', e.isAllCheck);
                setIndeterminate(e.code && !e.isAllCheck ? true : false);
                setIsChecked(e.isAllCheck || false);
                setCode(e.code || '');
              }}
            />
          </>
        ),
      },
    ];
  }, [code, indeterminate, isChecked, props]);

  return (
    <>
      <Collapse
        className={OStyle.tradeGToupBox}
        items={items}
        defaultActiveKey={['all']}
        expandIconPosition="end"
        collapsible="icon"
      />
    </>
  );
}
export default memo(TradeGroupSelect);
